package com.meng.mmlive.mvp.presenter;

import com.meng.mmlive.api.ApiClient;
import com.meng.mmlive.entity.Adverts;
import com.meng.mmlive.entity.AdvertsAndMainMenu;
import com.meng.mmlive.entity.BaseResponseData;
import com.meng.mmlive.entity.HomeMenu;
import com.meng.mmlive.mvp.view.HomeView;

import java.util.List;

import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.BiFunction;
import io.reactivex.schedulers.Schedulers;
import okhttp3.FormBody;

/**
 * Created by Administrator on 2017/5/13.
 */

public class HomePresenter extends BasePresenterImpl<HomeView> {
    public void loadData() {
        getView().showInitLoadingView();
        FormBody formBody = new FormBody.Builder()
                .add("head","{\"session\":\"\",\"sysCode\":2,\"sysInfo\":\"Xiaomi_MI 5_6.0.1\",\"userId\":-1,\"version\":\"2.3.4\"}")
                .build();
        Observable<BaseResponseData<List<Adverts>>> adverts = ApiClient.instance().getAdverts(formBody);
        Observable<BaseResponseData<List<HomeMenu>>> menuList = ApiClient.instance().getMenuList(formBody);
        Observable.zip(adverts, menuList, new BiFunction<BaseResponseData<List<Adverts>>, BaseResponseData<List<HomeMenu>>, AdvertsAndMainMenu>() {
            @Override
            public AdvertsAndMainMenu apply(BaseResponseData<List<Adverts>> listBaseResponseData, BaseResponseData<List<HomeMenu>> listBaseResponseData2) throws Exception {
                return new AdvertsAndMainMenu(listBaseResponseData,listBaseResponseData2);
            }
        }) .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(this::onFetchSuccess, this::onFetchFailed);
    }

    private void onFetchFailed(Throwable throwable) {
        if(getView() != null){
            getView().showInitLoadFailed(throwable);
            getView().hideInitLoadingView();
        }
    }

    private void onFetchSuccess(AdvertsAndMainMenu advertsAndMainMenu) {
        if(getView() != null){
            getView().showAdverts(advertsAndMainMenu.getResponseAdverts().getDataCollection());
            getView().showMainMenus(advertsAndMainMenu.getResponseMainMenu().getDataCollection());
            getView().hideInitLoadingView();
            getView().showRefreshComplete();
        }
    }
}
